<template>
  <view class="content">
    <view style="height: 100upx;" v-for="(item,index) in list" :key="item.id">
      {{item.title}}
    </view>

    <button @tap="loadMoreSearchResult">{{loadingMessage}}</button>
  </view>
</template>

<script>
  // import api from '@/common/api/index.js' //导出整个模块
  // 或者使用以下语法单独导出子模块
  import {
    company
  } from '@/common/api/index.js'

  export default {
    data() {
      return {
        loadingType: 0, //上拉的状态：0-loading前；1-loading中；2-没有更多了
        page: 0,
        list: [],
      }
    },
    computed: {
      loadingMessage() {
        const msg = ['上拉加载更多', '正在加载中', '没有更多数据了']
        return msg[this.loadingType];
      }
    },

    async onPullDownRefresh() {

      this.list = []; //清除已经加载的数据
      this.loadingType = 0; //恢复默认的状态

      await this.loadMoreSearchResult() //模拟加载一次数据

      setTimeout(() => {
        uni.stopPullDownRefresh()
      }, 1000)
    },

    async onLoad() {
      await this.loadMoreSearchResult()
    },
    async onReachBottom() {
      await this.loadMoreSearchResult();
    },
    methods: {

      async loadMoreSearchResult() {
        //上拉的状态：0-loading前；1-loading中；2-没有更多了
        if (this.loadingType !== 0) {
          return;
        }
        this.loadingType = 1;
        this.page = this.page + 1;

        //使用Es2017语法
        let response = await company.getList({
          page: this.page
        });

        if (response.errno === 0) {

          console.log(JSON.stringify(response));
          this.list = this.list.concat(response.data.data);

          if (response.data.totalPages == response.data.currentPage) {
            this.loadingType = 2; //2-没有更多了
          } else {
            this.loadingType = 0; //开启新一轮加载
          }
        } else {
          //
          this.loadingType = 0; //开启新一轮加载
        }
      }
    }
  }
</script>

<style>
  .content {
    text-align: center;
  }
</style>
